import os

import ezdxf
from shapely.geometry import Polygon
import math

def is_closed_rectangle(entity):
    """检查实体是否为闭合矩形"""
    if entity.dxftype() != 'LWPOLYLINE' or not entity.is_closed:
        return False
    if len(entity) != 4:
        return False
    return True

def get_entity_polygon(entity):
    """将 DXF 实体转换为 Shapely 的 Polygon"""
    points = [(point[0], point[1]) for point in entity]
    return Polygon(points)

def detect_enclosure_and_distance(dxf_path, target_coords):
    doc = ezdxf.readfile(dxf_path)
    msp = doc.modelspace()

    target_poly = Polygon(target_coords)
    closest_distance = float('inf')
    closest_entity = None
    closest_geom = None

    for e in msp:
        if is_closed_rectangle(e):
            rect_poly = get_entity_polygon(e)

            # 判断是否包含或相交
            if rect_poly.contains(target_poly) or rect_poly.intersects(target_poly):
                # 计算最短距离（即边界之间距离）
                distance = rect_poly.exterior.distance(target_poly.exterior)

                if distance < closest_distance:
                    closest_distance = distance
                    closest_entity = e
                    closest_geom = rect_poly

    if closest_entity:
        print("✅ 最近图元类型: RECTANGLE")
        print("📏 最近距离: {:.3f}".format(closest_distance))
        print("📍 最近图元坐标（Polygon）:", list(closest_geom.exterior.coords)[0])
    else:
        print("未找到包裹或重叠的闭合矩形。")

if __name__ == "__main__":
    # 当前脚本所在目录
    base_dir = os.path.dirname(__file__)

    # 相对路径构建 DXF 文件路径
    dxf_path = os.path.join(base_dir, "drawingLibrary", "嘉兴海宁全1.dxf")

    # 示例坐标（无需修改）
    block_coords = [(137353, 15900), (137353, 16100), (139143, 16100), (139143, 15900)]  # 注意坐标顺序必须构成有效Polygon

    # 调用函数
    detect_enclosure_and_distance(dxf_path, block_coords)
